<!--
 * @Description: 下发任务弹窗
 * @Author: Caroline
 * @Date: 2024-01-16 20:06:43
 * @LastEditTime: 2024-03-13 20:18:27
 * @LastEditors: Caroline
 * @FilePath: \Evaluation-web\src\views\task\detail\components\distributeTaskDialog.vue
-->
<template>
  <el-dialog v-model="visible" width="760px" title="下发任务" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" class="data-form" :rules="rules" :inline="true" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" label-width="120px">
      <!-- 点位下发方式 -->
      <el-form-item prop="issueModel" label="点位下发方式">
        <el-radio-group v-model="dataForm.issueModel">
          <el-radio :label="0">全部下发</el-radio>
          <el-radio :label="1">逐个下发</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 监测人员 -->
      <el-form-item prop="monitorUserId" label="监测人员">
        <el-select v-model="dataForm.monitorUserId" placeholder="监测人员">
          <el-option v-for="item in monitorList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <!-- 备注 -->
      <el-form-item prop="issueNotes" label="备注">
        <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 6 }" v-model="dataForm.issueNotes" :placeholder="$t('task.notes')"></el-input>
      </el-form-item>

      <!-- 附件 -->
      <el-form-item prop="fileList" label="附件">
        <el-upload drag accept=".xlsx,.xls,.xlsm,.csv" :limit="1" :http-request="onUploadFile" v-model:file-list="dataForm.fileList">
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">点击或拖动文件上传</div>
          <div class="el-upload__text tip">严禁上传包含色情、暴力、反动等相关违法信息的文件。</div>
        </el-upload>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">下发</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { ElLoading, ElMessage } from "element-plus";
import { useI18n } from "vue-i18n";
import baseService from "@/service/baseService";

const { t } = useI18n();

const emit = defineEmits(["refreshDataList"]);
const visible = ref(false);

const dataFormRef = ref();

type FormDataType = {
  taskId: string | number;
  userId: string;
  issueModel?: number;
  monitorUserId?: string;
  pointIds?: string[];
  issueNotes?: string;
  fileList?: string[];
};
const dataForm = ref<FormDataType>({
  taskId: "",
  issueModel: 1,
  userId: "",
  monitorUserId: "",
  issueNotes: "",
  pointIds: [],
  fileList: []
});

// 监测人员集合--系统用户
const monitorList = ref<{ id: string; name: string }[]>([]);
const getMonitorListList = () => {
  baseService.get("/sys/user/list").then((res) => {
    monitorList.value = (res.data || [])?.map(({ id, realName }: { id: string; realName: string }) => {
      return { id, name: realName };
    });
  });
};
getMonitorListList();

// 上传文件
const onUploadFile = async (param: any) => {
  const File = param.file;
  const formData1 = new FormData();
  formData1.append("file", File);
  const loading = ElLoading.service({
    lock: true,
    text: "正在上传",
    background: "rgba(0, 0, 0, 0.1)"
  });
  try {
    baseService
      .post("/assess/point/import/search", formData1)
      .then((res) => {
        loading.close();
        if (res.data.errorUrl) {
          ElMessage.warning("上传文件中存在错误数据，请检查");
          let a = document.createElement("a");
          a.download = "点位上传错误文件.xlsx"; //指定下载的文件名
          a.href = res.data.errorUrl;
          a.click(); // 模拟点击
          URL.revokeObjectURL(a.href); // 释放URL 对象
          dataForm.value.fileList = [];
        } else {
          console.log("dataForm.value.fileList==", dataForm.value.fileList);
          dataForm.value.pointIds = res.data?.ids;
          ElMessage.success("上传成功");
        }
      })
      .catch((err) => {
        dataForm.value.fileList = [];
        ElMessage.warning("上传附件异常");
        loading.close();
      });
  } catch (e) {
    param.onError(e);
  }
};

// 初始化
const init = (row: any) => {
  visible.value = true;
  dataForm.value.fileList = [];
  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }
  const { taskUserDTO } = row;
  dataForm.value = {
    taskId: taskUserDTO.taskId,
    userId: taskUserDTO.userId,
    issueModel: 1
  };
};

// 表单rules
const rules = ref({
  issueModel: [{ required: true, message: t("validate.required"), trigger: ["blur", "change"] }],
  monitorUserId: [{ required: true, message: t("validate.required"), trigger: ["blur", "change"] }]
  // fileList: [{ required: true, message: t("validate.required"), trigger: ["blur", "change"] }]
});

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    const { taskId, userId, issueNotes, issueModel, pointIds, monitorUserId } = dataForm.value;

    const params = {
      issueNotes,
      issueModel,
      pointIds,
      userId: userId,
      monitorUserId: monitorUserId,
      taskId
    };
    baseService.post("/assess/assesstaskissue", params).then((res) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({
  init
});
</script>
<style lang="less" scoped>
.title {
  line-height: var(--el-dialog-font-line-height);
  font-size: var(--el-dialog-title-font-size);
  color: var(--el-text-color-primary);
}
:deep(.el-form-item) {
  width: 100%;
}
.search-form {
  .el-form-item {
    width: auto;
  }
}
.data-form {
  .tip {
    color: #00000073;
  }
  :deep(.el-upload) {
    width: 600px;
  }
}
</style>
